package cn.tedu.ivos.audit.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos.audit.pojo.entity.Audit;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.base.enums.AuditStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

/*@Taransactional 是spring提供的一个用于进行事务管理的注解，可以管理类或方法上的事务行为
* 在我们对数据库做操作的时候，可以确保类中的方法对数据库的操作是在一个事务中进行的，要么都成功，要么都失败*/
@Transactional
@Slf4j
@Service
public class AuditServiceImpl implements AuditService {

    @Autowired
    AuditMapper auditMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ApplicationMapper applicationMapper;

    @Override
    public void insertAudit(Application app) {
        log.debug("新增申请单对应的审批单业务，参数："+app);
        List<Long> userIdList=app.getAuditUserIdList();
        for (int i=0;i < userIdList.size();i++){
            Audit audit = new Audit();
            audit.setApplicationId(app.getId());
            audit.setAuditUserId(userIdList.get(i));
            audit.setAuditSort(i);
            if (i==0){
                audit.setAuditStatus(AuditStatusEnum.MY_PENDIND.getCode());
            }else {
                audit.setAuditStatus(AuditStatusEnum.PENDING.getCode());
            }
            audit.setCreateTime(new Date());
            auditMapper.insertAudit(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long id) {
        return auditMapper.selectAuditByApplicationId(id);
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery query) {
        log.debug("查询审批单业务参数："+query);
        List<AuditVO>list=auditMapper.selectAudit( query);
        for(int i = 0; i < list.size(); i++){
            AuditVO auditVO = list.get(i);
            assignAuditUserList(auditVO);
        }
        return list;
    }


    private void assignAuditUserList(AuditVO auditVO) {
        List<String> auditUsernameList = new ArrayList<>();
        List<Long> auditUserIdList = new ArrayList<>();
        List<AuditVO> auditVOList =
                auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        for(int i = 0; i < auditVOList.size(); i++){
            Long userId = auditVOList.get(i).getAuditUserId();
            auditUserIdList.add(userId);
            UserVO userVO = userMapper.selectById(userId);
            auditUsernameList.add(userVO.getUsername());
        }
        StringJoiner stringJoiner = new StringJoiner(",");
        for(String username : auditUsernameList){
            stringJoiner.add(username);
        }
        auditVO.setAuditUserIdList(auditUserIdList);
        auditVO.setAuditUsernameList(stringJoiner.toString());
    }

    @Override
    public void updateAudit(AuditSaveParam param) {
        log.debug("更新审批单业务参数："+param);
        Audit audit = new Audit();
        BeanUtils.copyProperties(param, audit);
        audit.setUpdateTime(new Date());
        //先更新当前操作的这个审批人对应的这条审批单
        auditMapper.updateAudit(audit);
        //还要更新上面审批人批的这个申请单
        Application application= new Application();
        application.setId(audit.getApplicationId());
        application.setUpdateTime(new Date());
        /* 需要判断是通过操作还是驳回操作，分头处理 */
        if (audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())){//通过
            //继续查是否还存在未审批的审批单
            AuditQuery auditQuery=new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            Integer count= auditMapper.selectRestAuditCount(auditQuery);
            if (count>0){//还有未审批的审批单
                //下一条审批单是上一条审批单（批同一个申请单&审批次序+1）
                auditQuery.setAuditSort(audit.getAuditSort()+1);
                List<AuditVO> auditVOList =auditMapper.selectAudit(auditQuery);
                if (auditVOList.size()>0){
                    AuditVO auditVO = auditVOList.get(0);
                    //创建第2个空对象，代表第2条审批单数据
                    Audit audit2 = new Audit();
                    audit2.setId(auditVO.getId());
                    audit2.setAuditStatus(AuditStatusEnum.MY_PENDIND.getCode());
                    audit2.setUpdateTime(new Date());
                    auditMapper.updateAudit(audit2);
                }
                //还需要将申请单改成 30 审核中
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.cancel(application);


            }else {//没有未审批的审批单
                //所以：申请单要更新成 50 已审核
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.cancel(application);
            }
        }else {//驳回
            AuditQuery query=new AuditQuery();
            query.setApplicationId(audit.getApplicationId());
            //查询审批此申请单对应的所有审批单（申请单id 就是上方更新的那条审批单的申请单id）
            List<AuditVO> auditVOList = auditMapper.selectAudit(query);
            if (auditVOList !=null && auditVOList.size()>0){
                for (int i=0;i<auditVOList.size();i++){
                    AuditVO auditVO = auditVOList.get(i);
                    //如果当前审批单的状态为待他人审核，也就是还未审核，就删除
                    if (auditVO.getAuditStatus().equals(AuditStatusEnum.PENDING.getCode())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(param.getRejectReason());
            applicationMapper.cancel(application);
        }

    }






















}


